package com.auth.Sercurity.TreadDemo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author hujian
 * @version 1.0
 * @description: ReentrantLock绑定条件
 * @date 2022/2/23 14:38
 */
public class ReentrantLockCondition {
    int number=1;
    private ReentrantLock lock=new ReentrantLock(true);
    private Condition condition1=lock.newCondition();
    private Condition condition2=lock.newCondition();
    private Condition condition3=lock.newCondition();

    void print1(){
        lock.lock();
        try {
            while (number!=1){
//                等待
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName()+"---"+number);
            number=2;
//            唤醒
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName()+"线程结束");
            lock.unlock();
        }
    }
    void print2(){
        lock.lock();
        try {
            while (number!=2){
//                等待
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName()+"---"+number);
            number=3;
//            唤醒
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName()+"线程结束");
            lock.unlock();
        }
    }void print3(){
        lock.lock();
        try {
            while (number!=3){
//                等待
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName()+"---"+number);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName()+"线程结束");
            lock.unlock();
        }
    }


    public static void main(String[] args) {
        ReentrantLockCondition reentrantLockCondition=new ReentrantLockCondition();
        new Thread(()->reentrantLockCondition.print2(),"B:").start();
        new Thread(()->reentrantLockCondition.print3(),"C:").start();
        new Thread(()-> reentrantLockCondition.print1(),"A:").start();

    }
}
